<template>
  <div class="app-container">
    <!--    <el-progress type="line" :format="recoderFormat" :stroke-width="10" :percentage="recoderSecond"></el-progress>-->
    <div v-if="isSound" v-show="isSound != 0">
      <div style="display: flex; justify-content: center; padding-bottom: 5px">
        <audio v-show="recorderEnd" controls ref="audio" muted="muted" src="" id="audio"></audio>
      </div>
      <div style="display: flex; justify-content: center; padding-bottom: 5px">
        <el-button size="mini" type="primary" @click="startRecoder()">开始录音
        </el-button>
        <el-button size="mini" type="success" @click="stopRecoder()">结束录音
        </el-button>
        <el-button size="mini" type="warning" @click="cancelRecoder()">取消录音
        </el-button>
      </div>
    </div>
    <el-form v-if="decryptId === 98" style="margin-bottom: 20px;" :rules="rules" label-position="top" ref="refForm"
      :model="form">
      <el-form-item label="酒店名称" prop="selectHotel">
        <el-select v-model="form.selectHotel" key="selectHotel.uniqueId" filterable>
          <el-option v-for="item in hotelList" :key="item.id" :label="item.hotelName" :value="item">{{
            item.hotelName
          }}</el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <form-create v-model="fApi" :rule="rule" :option="option" :value.sync="value"></form-create>
  </div>
</template>

<script>
import { surveryInfo, uploadWAVFile } from "@/api/survery/form";
import { saveSurvery, getHotelList } from "@/api/survery/data";
import Recorder from "js-audio-recorder";
import axios from "axios";
import { Notification, MessageBox, Message, Loading, Descriptions } from "element-ui";
//const filename2 = new Date().getTime();

var recorder;
let LoadingS;

import "../../../utils/crypto1/crypto/crypto";
import "../../../utils/crypto1/hmac/hmac";
import "../../../utils/crypto1/sha1/sha1";
import { Base64 } from "js-base64";
import { encrypt, decrypt } from "@/utils/jsencrypt";

/**
 * 生成policy和签名
 * 默认1小时后失效
 * @param {*} accessKeySecret oss accessKeySecret
 * @param {*} expiration 过期时间 单位秒
 * @returns
 */
function genSignature(fileName) {
  const accessKeySecret = "ZNVPLxgMYGa7CZsghYOVnyOyyJOGFv";
  const expiration = new Date(Date.now() + 1200 * 1000).toISOString();
  const policy = {
    expiration: expiration, // 失效时间
    conditions: [
      ["content-length-range", 0, 469824028], // 设置上传文件的大小限制 1G
    ],
  };
  const policyBase64 = Base64.encode(JSON.stringify(policy));

  const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accessKeySecret, {
    asBytes: true,
  });
  const signature = Crypto.util.bytesToBase64(bytes);

  return {
    OSSAccessKeyId: "LTAI5tEewCaBy7zsdcL6GmVT",
    policy: policyBase64,
    key: fileName,
    success_action_status: "200",
    signature,
  };
}



var date = new Date();
var fileS =
  date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + date.getDate() + "/";
export default {
  name: "index",
  data() {
    return {
      //实例对象
      fApi: {},
      //表单数据
      value: {},
      //表单生成规则
      rule: [],
      //组件参数配置
      option: {},
      isSound: undefined,
      recoderSecond: 0,
      recorderAudio: null,
      talkBtnText: "按住 说话",
      recorderEnd: true,
      isSubmitting: false,
      decryptId: 0,
      hotelList: [],
      form: {},
      valid: undefined,
      rules: {
        selectHotel: [{ required: true, message: '请选择酒店名称', trigger: 'change' },]
      }
    };
  },
  created() {
    console.log("this.$route.query.id", this.$route.query.id);
    var descrip = Crypto.util.bytesToString(
      Crypto.util.wordsToBytes([
        Crypto.util.bytesToString(
          Crypto.util.base64ToBytes(this.$route.query.id)
        ),
      ])
    );
    this.decryptId = parseInt(descrip);
    this.getSurveyInfo(this.decryptId);
    console.log("decryptId--->", this.decryptId)
    if (this.decryptId === 98) {
      this.getHotelList();
    }
  },
  methods: {
    getHotelList() {
      var date = new Date().toLocaleDateString().replaceAll("/", "-");
      const data = { creatDate: date };
      getHotelList(data).then(res => {
        this.hotelList = [];
        this.hotelList = res.rows;
        console.log("hotelList", this.hotelList)
      })
    },
    getSurveyInfo(e) {
      surveryInfo(e).then((res) => {
        //处理规则中类型为上传的控件信息
        console.log("res--->", res)

        var rule = res.data.rtformRules;
        this.isSound = res.data.isSound;
        for (var i = 0; i < res.data.rtformRules.length; i++) {
          var randomNum = Math.floor(Math.random() * (99999 - 55 + 1)) + 55;
          if (rule[i].type == "upload") {
            //const filename2 = new Date().getTime()+"_"+i;
            var filename2 = "";
            console.log("111", randomNum)
            var fileList = [];
            var title = rule[i].title;
            rule[i].props.fileList = fileList;
            (rule[i].props.httpRequest = function (file) {
              const params = new FormData();
              var fileName = e + "/" + fileS + randomNum + file.file.name;
              console.log("111", fileName)
              console.log("111", fileName.length)
              const data = genSignature(fileName);
              params.append("OSSAccessKeyId", data.OSSAccessKeyId);
              params.append("key", fileName);
              params.append(
                "success_action_status",
                data.success_action_status
              );
              params.append("signature", data.signature);
              params.append("policy", data.policy);
              params.append("file", file.file);
              const config = {
                headers: {
                  Accept: "*/*",
                  "Content-Type": "multipart/form-data",
                },
              };
              axios.post(file.action, params, config).then((res) => {
                file.onSuccess(res);
                const data = {
                  name: file.file.name,
                  url: "http://img.cscxsk.cn/" + fileName,
                };
                file.response = data;
                fileList.push(file);
              });
            }),
              (rule[i].props.onSuccess = function (res, file, fileList) {
                file.url =
                  "http://img.cscxsk.cn/" + e + "/" + fileS + randomNum + encodeURIComponent(file.name);
                console.log(file.url);
                console.log(fileList)
                Message({ message: title + "上传成功!", type: "success" });
                LoadingS.close();
              });
            rule[i].props.beforeUpload = function (file) {
              LoadingS = Loading.service({
                text: "正在上传，请稍候",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)",
              });
            };
            rule[i].props.onError = function (file) {
              Message({ message: title + "上传失败!", type: "error" });
              LoadingS.close();
            };
          }
        }
        this.rule = rule;
        //处理form表单 默认提交按钮
        this.option = res.data.rtformOption;
        let _this = this
        this.option.onSubmit = async function (formData) {
          console.log("打印日志", _this.isSubmitting)
          if (_this.isSubmitting) {
            console.log("防止重复提交")
            return
          };
          _this.isSubmitting = true;
          try {
            if (recorder) {
              var blob = recorder.getWAVBlob();
              var formDataq = new FormData();
              // 此处获取到blob对象后需要设置fileName满足当前项目上传需求，其它项目可直接传把blob作为file塞入formData
              const newbolb = new Blob([blob], { type: "audio/wav" });
              //获取当时时间戳作为文件名
              const fileOfBlob = new File(
                [newbolb],
                new Date().getTime() + ".wav"
              );
              formDataq.append("file", fileOfBlob);
              await axios
                .post(
                  process.env.VUE_APP_BASE_API + "/common/AliUpload",
                  formDataq
                )
                .then((res) => {
                  console.log(res.data);
                  formData["录音地址"] = res.data.url;
                  for (var key in formData) {
                    if (typeof formData[key] == "object") {
                      formData[key] = formData[key].join(",");
                    }
                  }
                  const data = { surverId: e, form: JSON.stringify(formData) };
                  saveSurvery(data).then((res) => {
                    alert("提交成功！");
                    location.reload();
                  });
                });
            } else {
              for (var key in formData) {
                if (typeof formData[key] == "object") {
                  formData[key] = formData[key].join(",");
                }
              }
              if (_this.decryptId === 98) {

                _this.getFormValid()
                if(!_this.valid){
                  _this.isSubmitting = false;
                  return;
                }
                console.log("_this.selectHotel", _this.form.selectHotel);
                formData['uniqueId'] = _this.form.selectHotel.uniqueId;
                formData['hotelId'] = _this.form.selectHotel.hotelId;
                formData['酒店名称'] = _this.form.selectHotel.hotelName;
              }

              const data = { surverId: e, form: JSON.stringify(formData) };
              console.log("data====>", data);
              await saveSurvery(data).then((res) => {
                alert("提交成功！");
                location.reload();
              });
            }
          } catch (error) {

            console.log("出错了", error)
          } finally {
            this.isSubmitting = false
          }
        };
        this.dialogVisible = true;
      });
    },
    async getFormValid() {
      await this.$refs.refForm.validate(valid => {
        console.log("valid====>", valid);
        this.valid = valid;
      });
    },
    startRecoder() {
      recorder = new Recorder();
      this.recorderAudio = document.querySelector("#audio");
      recorder.start();
    },
    stopRecoder() {
      if (!recorder) {
        return;
      }
      var blob = recorder.getWAVBlob();
      document.querySelector("#audio").src = URL.createObjectURL(blob);
      document.querySelector("#audio").controls = true;
      // var formDataq = new FormData()
      // // 此处获取到blob对象后需要设置fileName满足当前项目上传需求，其它项目可直接传把blob作为file塞入formData
      // const newbolb = new Blob([blob], { type: 'audio/wav' })
      // //获取当时时间戳作为文件名
      // const fileOfBlob = new File([newbolb], new Date().getTime() + '.wav')
      // formDataq.append('file', fileOfBlob)
      // axios.post(process.env.VUE_APP_BASE_API+"/common/AliUpload",formDataq)
    },
    cancelRecoder() {
      this.recoderSecond = 0;
      if (!recorder) {
        return;
      }
      recorder.destroy();
      document.querySelector("#audio").src = "";
      recorder = null;
    },
  },
};
</script>

<style scoped>
::v-deep .el-icon-delete {
  position: absolute;
  top: 0;
  right: 0;
}

::v-deep .fc-files {
  width: 100px;
  height: 100px;
}

::v-deep .fc-upload-btn {
  width: 100px;
  height: 100px;
}

::v-deep .el-icon-view {
  position: absolute;
  top: 40px;
  right: 40px;
}

::v-deep .el-icon-upload2 {
  position: absolute;
  top: 40px;
  right: 43px;
}
</style>
